#include "lua-worker.h"
#include <memory>

void LuaWorker::set_script(const std::string &script) { script_ = script; }

LuaWorker::LuaWorker(const std::string &file_path,
                     const std::string &file_root_path,
                     const std::shared_ptr<Game> game,
                     const std::shared_ptr<Api> api)
    : file_path_{file_path}, file_root_path_{file_root_path} {
  engine_ = std::make_shared<LuaEngine>();
  api_ = std::make_shared<LuaApi>(game, api);
  // 注册 lua api
  *static_cast<LuaApi **>(lua_getextraspace(engine_->lptr())) = &(*api_);
  engine_->reg();
}

LuaWorker::~LuaWorker() {}

void LuaWorker::work(void *context) {
  if (script_.empty()) {
    dbgprintu8("codergege [%s][%03d] %s 脚本开始执行\n", __FUNCTION__, __LINE__,
               file_path_.c_str());
    engine_->dofile(file_root_path_ + "\\_common.lua");
    engine_->dofile(file_path_);
    dbgprintu8("codergege [%s][%03d] %s 脚本执行结束\n", __FUNCTION__, __LINE__,
               file_path_.c_str());
  } else {
    engine_->dofile(file_root_path_ + "\\_common.lua");
    engine_->dostring(script_);
  }
  delete this;
}

void LuaWorker::abort() { delete this; }
